package listener;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebListener
public class UserCountListener implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        /* Session is created. 当session创建出来的时候，执行这个方法+1*/
        //ctx存在线人数数据的地方
        ServletContext ctx = se.getSession().getServletContext();
        Integer count = (Integer) ctx.getAttribute("OnlineCount");
        if (count == null) {
            count = 0;
        }
        count++;
        ctx.setAttribute("OnlineCount", count);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        /* Session is destroyed. 销毁 —1*/
        /* Session is created. 当session创建出来的时候，执行这个方法+1*/
        //ctx存在线人数数据的地方
        ServletContext ctx = se.getSession().getServletContext();
        Integer count = (Integer) ctx.getAttribute("OnlineCount");
        if (count == null) {
            count = 0;
        }
        count--;
        ctx.setAttribute("OnlineCount", count);
    }

}